package com.gz.purchase.app;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.purchase.R;
import com.gz.purchase.adapter.SpinnerAdapter;
import com.gz.purchase.adapter.StorageCheckAdapter;
import com.gz.purchase.library.IAuthor;
import com.gz.purchase.library.IProduct;
import com.gz.purchase.library.listener.GetShopListListener;
import com.gz.purchase.library.listener.GetStorageCheckProductslistener;
import com.gz.purchase.library.listener.PutIntoOutStorageCartListener;
import com.gz.purchase.library.listener.RequestCode;
import com.gz.purchase.library.pojo.CustomerSpinnerObject;
import com.gz.purchase.library.pojo.ShopInfo;
import com.gz.purchase.library.pojo.StorageCheckProductInfo;
import com.gz.purchase.library.pojo.UserInfo;
import com.gz.purchase.library.util.Constants;
import com.gz.purchase.library.util.CrashHandler;
import com.gz.purchase.library.util.PreferenceModel;
import com.gz.purchase.util.ToastUtils;
import com.gz.purchase.widget.FooterView;
import com.gz.purchase.widget.LoadingCover;
import com.gz.purchase.widget.SpinerPopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.lang.ref.WeakReference;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 库存查看界面
 */
public class StorageCheckActivity extends BaseActivity implements View.OnClickListener,
        FooterView.OnFooterViewRefreshListener, LoadingCover.OnLoadingCoverRefreshListener,
        SpinerPopWindow.ISpinnerOnItemSelectListener {
    private String TAG = StorageCheckActivity.class.getSimpleName();
    private ImageView iv_actionbar_up;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private EditText et_search_content;  // 搜索文本框
    private ImageView iv_search_delete;  // 删除按钮
    private ImageView iv_search_trigger; // 搜索按钮

    private TextView tv_add_to_outStorageCart;//加入出库车
    private RelativeLayout rl_choice_for_shop;//商家选择
    private RelativeLayout rl_choice_for_order; //排序
    private PullToRefreshListView mPullListView;
    private FooterView mFooterView;
    private Dialog mLoadingData;
    private LoadingCover mLoadingCover;
    private StorageCheckAdapter mAdapter;
    private List<StorageCheckProductInfo> mDataList;

    private MyGetStorageCheckProductslistener mPullListener;
    private MyGetStorageCheckProductslistener mScrollListener;
    private MyGetShopListListener myGetShopListListener;
    private MyPutIntoOutStorageCartListener myPutIntoOutStorageCartListener;

    private List<CustomerSpinnerObject> shopList;
    private SpinnerAdapter partSpinnerAdapter;
    private SpinerPopWindow mPartSpinnerPopWindow;

    private UserInfo info;
    private int page;
    private int shop_id = -1;// 当前选中的商铺id
    private int order_type = -1;
    private String product_name = null;// 当前在搜索框输入的商品名

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_storage_check);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.common_activity_head_layout);//自定义ActionBar布局
        initView();
        initListener();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mScrollListener.release();
        mPullListener.release();
        myGetShopListListener.release();
        myPutIntoOutStorageCartListener.release();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_search_trigger: // 点击搜索
                product_name = et_search_content.getText().toString();
                if (TextUtils.isEmpty(product_name)) {
                    ToastUtils.showToast(this, "请输入商品名称");
                    return;
                }
                mLoadingData.show();
                shop_id = -1;
                page = 1;
                // 把所有商家置为未选中状态
                if (shopList.size() > 0) {
                    for (int i = 0; i < shopList.size(); i++) {
                        shopList.get(i).setIsSelected(false);
                    }
                }
                IProduct.getInstance().getStorageCheckProducts(shop_id, product_name, order_type, page, mPullListener);
                break;
            case R.id.iv_search_delete: // 点击删除按钮
                et_search_content.setText("");
                break;
            case R.id.iv_actionbar_up: // 返回
                shop_id = -1;
                product_name = null;
                finish();
                break;
            case R.id.rl_choice_for_shop: // 点击商家选择按钮
                if (shopList.size() == 0) {
                    ToastUtils.showToast(this, "商家列表为空");
                    return;
                }
                mPartSpinnerPopWindow.setWidth(rl_choice_for_shop.getWidth() * 2);
                mPartSpinnerPopWindow.showAsDropDown(rl_choice_for_shop);
                break;
            case R.id.tv_add_to_outStorageCart: // 点击加入出库车
                addToOutStorageCart();
                break;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            shop_id = -1;
            product_name = null;
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 上拉加载， 商铺id 商品名 仍然保持和上一次一样，page++
    @Override
    public void onFooterViewRefresh() {
        //下面这个判断是为了防止用户在 该界面刚加载出来时就点击 FooterView 执行onFooterViewRefresh()方法 ，这是不允许的，必须给出选择条件
        if (shop_id == -1 && product_name == null) {
            return;
        }
        page++;
        IProduct.getInstance().getStorageCheckProducts(shop_id, product_name, order_type, page, mScrollListener);

    }

    @Override
    public void onLoadingCoverRefresh() {
        IProduct.getInstance().getShopList(myGetShopListListener);
    }

    // 点击商家条目触发一下方法
    @Override
    public void onSpinnerItemClick(int position) {
        mLoadingData.show();
        for (int i = 0; i < shopList.size(); i++) {
            if (i == position) {
                shopList.get(i).setIsSelected(true);
            } else {
                shopList.get(i).setIsSelected(false);
            }
        }
        ShopInfo info = (ShopInfo) shopList.get(position);
        product_name = null;
        et_search_content.setText("");
        shop_id = info.getShop_id();
        page = 1;
        IProduct.getInstance().getStorageCheckProducts(shop_id, product_name, order_type, page, mPullListener);

    }

    private void initView() {
        info = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        iv_actionbar_up = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);

        et_search_content = (EditText) this.findViewById(R.id.et_search_content);
        iv_search_delete = (ImageView) this.findViewById(R.id.iv_search_delete);
        iv_search_trigger = (ImageView) this.findViewById(R.id.iv_search_trigger);

        tv_add_to_outStorageCart = (TextView) this.findViewById(R.id.tv_add_to_outStorageCart);
        rl_choice_for_shop = (RelativeLayout) this.findViewById(R.id.rl_choice_for_shop);
        rl_choice_for_order = (RelativeLayout) this.findViewById(R.id.rl_choice_for_order);

        mLoadingCover = (LoadingCover) this.findViewById(R.id.layout_loading_cover);
        mPullListView = (PullToRefreshListView) this.findViewById(R.id.list);
        mFooterView = (FooterView) LayoutInflater.from(this).inflate(R.layout.footer_view, null);
        mFooterView.onRefreshSuccess("");
        mPullListView.getRefreshableView().addFooterView(mFooterView);

        mLoadingData = new Dialog(this, R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);

    }

    private void initListener() {
        iv_actionbar_up.setOnClickListener(this);
        iv_search_delete.setOnClickListener(this);
        iv_search_trigger.setOnClickListener(this);
        tv_add_to_outStorageCart.setOnClickListener(this);

        rl_choice_for_shop.setOnClickListener(this);

        mLoadingCover.setOnLoadingCoverRefreshListener(this);
        mPullListener = new MyGetStorageCheckProductslistener(RequestCode.PULL, this);
        mPullListView.setMode(PullToRefreshBase.Mode.DISABLED);
        mScrollListener = new MyGetStorageCheckProductslistener(RequestCode.SCROLL, this);
        myGetShopListListener = new MyGetShopListListener(this);
        myPutIntoOutStorageCartListener = new MyPutIntoOutStorageCartListener(this);

        mFooterView.setOnFooterViewRefreshListener(this);
        mPullListView.setOnScrollListener(mFooterView);

        et_search_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(et_search_content.getText().toString())) {
                    iv_search_delete.setVisibility(View.GONE);
                } else {
                    iv_search_delete.setVisibility(View.VISIBLE);
                }


            }
        });
        //监听键盘上的enter键
        et_search_content.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg1 == KeyEvent.KEYCODE_ENTER) {
                    String content = et_search_content.getText().toString();
                    if (!TextUtils.isEmpty(content)) {
                        mLoadingData.show();
                        // 把所有商家置为未选中状态
                        if (shopList.size() > 0) {
                            for (int i = 0; i < shopList.size(); i++) {
                                shopList.get(i).setIsSelected(false);
                            }
                        }
                        product_name = et_search_content.getText().toString();
                        shop_id = -1;
                        page = 1;
                        IProduct.getInstance().getStorageCheckProducts(shop_id, product_name, order_type, page, mPullListener);
                    }
                    return true;
                }
                return false;
            }
        });
    }

    private void initData() {
        tv_actionbar_title.setText("库存查看");
        if (info != null) {
            tv_actionbar_deliveryName.setText(info.getName() + "：" + info.getUser_name());
        }
        mDataList = new ArrayList<StorageCheckProductInfo>();
        mAdapter = new StorageCheckAdapter(this, mDataList);
        mPullListView.setAdapter(mAdapter);

        // 初始化"商家选择" 控件
        shopList = new ArrayList<CustomerSpinnerObject>();
        partSpinnerAdapter = new SpinnerAdapter(this, shopList);
        mPartSpinnerPopWindow = new SpinerPopWindow(this);
        mPartSpinnerPopWindow.setAdatper(partSpinnerAdapter);
        mPartSpinnerPopWindow.setItemListener(this);

        IProduct.getInstance().getShopList(myGetShopListListener);

    }


    public void addToOutStorageCart() {
        if (mDataList.size() == 0) {
            mLoadingData.dismiss();
            ToastUtils.showToast(this, "商品列表为空");
            return;
        }
        mLoadingData.show();
        // 循环遍历找到所有选中的订单
        ArrayList<String> sellectedOrdes = new ArrayList<String>();
        for (int i = 0; i < mDataList.size(); i++) {
            StorageCheckProductInfo info = mDataList.get(i);
            if (info.isSelected()) {
                sellectedOrdes.add(info.getProduct_id() + "");
            }
        }

        if (sellectedOrdes.size() <= 0) {
            mLoadingData.dismiss();
            ToastUtils.showToast(this, "请先选择商品");
            return;
        } else {
            // 把选中的商品id拼成以逗号隔开的字符串
            StringBuilder str = new StringBuilder("");
            for (int j = 0; j < sellectedOrdes.size(); j++) {
                if (j == 0) {
                    str.append(sellectedOrdes.get(j));
                } else {
                    str.append("," + sellectedOrdes.get(j));
                }
            }
            if (str != null && !(str.toString().equals(""))) {
                CrashHandler.i(TAG, str.toString());
                IProduct.getInstance().putProductIntoOutStorageCart(str.toString(), myPutIntoOutStorageCartListener);

            } else {
                mLoadingData.dismiss();
                ToastUtils.showToast(this, "请先选择商品");
            }

        }

    }

    /**
     * 获取库存商品回调监听器
     */
    private static class MyGetStorageCheckProductslistener extends GetStorageCheckProductslistener {
        private StorageCheckActivity mOuter;

        public MyGetStorageCheckProductslistener(RequestCode requestCode, StorageCheckActivity mOuter) {
            super(requestCode);
            this.mOuter = mOuter;
        }

        public void release() {
            new WeakReference<StorageCheckActivity>(mOuter);
        }

        @Override
        public void onSatisfiedStorageProducts() {
            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPullListView.setOnScrollListener(null);

            if (getRequestCode() == RequestCode.PULL) {
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
                mOuter.mFooterView.onRefreshSuccess("无满足条件的商品");
                mOuter.mPullListView.setOnScrollListener(null);
                ToastUtils.showToast(mOuter, "无满足条件的商品");
            }


            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }


        }

        @Override
        public void onResponseSuccess(List<StorageCheckProductInfo> storageCheckProducts) {
            if (storageCheckProducts == null) {
                storageCheckProducts = new ArrayList<StorageCheckProductInfo>();
            }
            if (getRequestCode() == RequestCode.PULL) {
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
            }
            if (storageCheckProducts.size() < Define.LISTVIEW_ITEM_MIN_SIZE) {
                mOuter.mFooterView.onRefreshComplete();
                mOuter.mPullListView.setOnScrollListener(null);
            } else {
                mOuter.mFooterView.onRefreshSuccess();
                mOuter.mPullListView.setOnScrollListener(mOuter.mFooterView);
            }
            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            mOuter.mDataList.addAll(storageCheckProducts);
            mOuter.mAdapter.notifyDataSetChanged();
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }

        }

        @Override
        public void onNoNetWork() {
            if (getRequestCode() == RequestCode.PULL) {
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
                mOuter.mFooterView.onRefreshSuccess("");
                mOuter.shop_id = -1;
                mOuter.product_name = null;
            } else if (getRequestCode() == RequestCode.SCROLL) {
                mOuter.mFooterView.onRefreshFailed();
                mOuter.page--;
            }
            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            if (getRequestCode() == RequestCode.PULL) {
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
                mOuter.mFooterView.onRefreshSuccess("");
                mOuter.shop_id = -1;
                mOuter.product_name = null;
            } else if (getRequestCode() == RequestCode.SCROLL) {
                mOuter.mFooterView.onRefreshFailed();
                mOuter.page--;
            }

            if (mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }

            ToastUtils.showToast(mOuter, Define.MSG_ON_RESPONSE_FAILED);


        }
    }

    /**
     * 获取商家列表回调监听器
     */
    private static class MyGetShopListListener extends GetShopListListener {
        private StorageCheckActivity mOuter;

        public MyGetShopListListener(StorageCheckActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release() {
            new WeakReference<StorageCheckActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess(List<ShopInfo> infos) {

            mOuter.shopList.addAll(infos);
            mOuter.mLoadingCover.onRefreshSuccess();
        }

        @Override
        public void onNoShopInfo() {
            mOuter.mLoadingCover.onRefreshSuccess();

        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingCover.onRefreshFailed(Define.MSG_LOADING_BY_CLICK);
            ToastUtils.showToast(mOuter, Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingCover.onRefreshFailed(Define.MSG_LOADING_BY_CLICK);
            ToastUtils.showToast(mOuter, "获取商家列表失败");

        }
    }

    /**
     * 放入出库车回调监听器
     */
    private static class MyPutIntoOutStorageCartListener extends PutIntoOutStorageCartListener {
        private StorageCheckActivity mOuter;

        public MyPutIntoOutStorageCartListener(StorageCheckActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release() {
            new WeakReference<StorageCheckActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess() {
            // 移除已经放入出库车的数据
            Iterator<StorageCheckProductInfo> iterator = mOuter.mDataList.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().isSelected()) {
                    iterator.remove();
                }
            }

            mOuter.mAdapter.notifyDataSetChanged();
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, "操作成功");

        }

        @Override
        public void onStorageISZeroOrAuthority(String msg) {
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, msg);

        }

        @Override
        public void onResponseFailed() {
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, "放入出库车失败");

        }
    }
}
